<!-- 疾病记录/疾病报表 -->
<template>
  <BaseMainSlot :show-btn-box="false">
    <template v-slot:searchbox>
      <el-collapse v-model="activeName" accordion @change="handleChange">
        <el-collapse-item name="1">
          <template slot="title">
            <div class="select-btns search-btns" @click.stop="changeSelect()">
              <i class="el-icon-circle-check"></i>
              <p v-if="activeName === '1'">收起筛选</p>
              <p v-if="activeName === ''">展开筛选</p>
            </div>
          </template>
          <div class="search-btn search-btns" @click.stop="searchPage()">
            <i class="el-icon-circle-check"></i>
            <p>查询</p>
          </div>

          <div class="select-box-content">
            <div class="select-box-content-name">发病鱼塘名称</div>
            <el-select filterable clearable v-model="fishPondId" filterable clearable @change="() => {
              productionBatchId = ''
            }">
              <el-option v-for="(item, index) in pondList" :key="index" :label="item.pondName" :value="item.fishPondId" />
            </el-select>
          </div>

          <div class="select-box-content">
            <div class="select-box-content-name">批次编号</div>
            <el-select filterable clearable v-model="productionBatchId" filterable clearable>
              <template v-for="(item, index) in batchList">
                <el-option v-if="!fishPondId || item.fishPondId == fishPondId" :key="index" :label="`${item.mnecode}_${item.varietyName}`"
                  :value="item.productionBatchId" />
              </template>
            </el-select>
          </div>

          <div class="select-box-content">
            <div class="select-box-content-name">发现人</div>
            <el-select filterable clearable v-model="discoverStaffId" filterable clearable>
              <el-option v-for="(item, index) in staffList" :key="index" :label="item.staffName" :value="item.staffId" />
            </el-select>
          </div>

          <div v-if="!dealFlag" class="select-box-content select-box-leng-content">
            <div class="select-box-content-name">发现日期</div>
            <el-date-picker v-model="happenTime" type="daterange" range-separator="至" start-placeholder="开始日期"
              end-placeholder="结束日期" value-format="yyyy-MM-dd HH:mm:ss" clearable />
          </div>
          <div v-else class="select-box-content select-box-leng-content">
            <div class="select-box-content-name">处理日期</div>
            <el-date-picker v-model="dealTime" type="daterange" range-separator="至" start-placeholder="开始日期"
              end-placeholder="结束日期" value-format="yyyy-MM-dd HH:mm:ss" clearable />
          </div>
        </el-collapse-item>
      </el-collapse>
    </template>

    <template v-slot:btnsBar>
      <ActionBar v-show="routerPath == '/healthTaskManagement'" :export-active="true" :hasExport="true"
        :add-active="addActive" :del-active="delActive" :page-no="162" @exportFile="exportFile" @add="add" @del="del" />
      <ActionBar v-show="routerPath == '/healthTaskManagement-sr'" :export-active="true" :hasExport="true" :hasAdd='false'
        :del-active="delActive" :page-no="162" @exportFile="exportFile" @del="del" />
    </template>
    <template v-slot:categoryBox>
      <CategoryBar :categoryList="categoryList" @categoryBar="categoryBar"
        v-show="routerPath !== '/healthTaskManagement-sr'" />
    </template>
    <template v-slot:content>
      <el-table ref="tableData" v-loading="loading" highlight-current-row :data="tableData" stripe border
        height="calc(100% - 50px)" :row-key="(row) => {
          return row.diseaseRecordId;
        }
          " @selection-change="handleSelectionChange" @select="select" @select-all="selectAll"
        @expand-change="expandChange">
        <el-table-column type="expand" v-if="dealFlag">
          <template slot-scope="props">
            <div class="table-expand-box" v-for="(item, index) in props.row['diseaseDealList']" :key="index">
              <div class="drugInfo">
                <div class="table-expand">
                  <div class="table-expand-item">
                    <div class="">处理人：</div>
                    <div class="">{{ item.staffName }}</div>
                  </div>
                  <div class="table-expand-item">
                    <div class="">水 温：</div>
                    <div class="">{{ item.waterTemperature }}</div>
                  </div>
                  <div class="table-expand-item">
                    <div class="">处理时间：</div>
                    <div class="">{{ item.dealDate }}</div>
                  </div>
                </div>
                <div class="serialNum">记录{{ index + 1 }}</div>
              </div>
              <div class="table-expand-drug" v-for="(drugInfo, drugIndex) in item['diseaseDealDetailList']"
                :key="drugIndex">
                <div class="table-expand-drugInfo">
                  <div class="table-expand-item">
                    <div class="titelStyle">用药名称：</div>
                    <div class="textStyle">
                      {{ drugInfo.materialName ? drugInfo.materialName : "无" }}
                    </div>
                  </div>
                  <div class="table-expand-item">
                    <div class="titelStyle">用药数量：</div>
                    <div class="textStyle">
                      {{ drugInfo.amount ? drugInfo.amount : "无" }}
                    </div>
                  </div>
                  <div class="table-expand-item">
                    <div class="titelStyle">药品用法：</div>
                    <div class="textStyle">
                      {{ drugInfo.usage ? drugInfo.usage : "无" }}
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column type="selection" width="55" :reserve-selection="true" :selectable="(row) => {
          return !row.selectable;
        }
          " />
        <el-table-column type="index" label="序号" width="50">
          <template slot-scope="scoped">{{
            scoped.row.diseaseRecordId ? scoped.$index + 1 : ""
          }}</template>
        </el-table-column>
        <el-table-column prop="diseaseName" label="疫病名称" />
        <el-table-column prop="num" label="患病数量（尾）" />
        <el-table-column prop="pondName" label="发病鱼塘名称" />
        <el-table-column prop="mnecode" label="发病批次编号" />
        <el-table-column prop="productionBatchCode" label="码单号" />
        <el-table-column prop="discoverStaffName" label="发现人" />
        <el-table-column prop="happenTime" label="发现时间" />
        <el-table-column label="操作" width="150">
          <template v-if="scoped.row.diseaseRecordId && mark == 'dealFlagNone'" slot-scope="scoped">
            <div class="table-btns-box">
              <div class="table-btns edit-btns" @click="edit(scoped.row)">
                <p>修改</p>
              </div>
              <div class="table-btns edit-btns" @click="delOne(scoped.row)">
                <p>删除</p>
              </div>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <ExportBtn ref="ExportBtn" :btnName="'疾病报表'" :apiName="'diseaseRecordExport'" :searchObj="searchObj"></ExportBtn>
      <Pagination :page-size="pageSize" :current-page="currentPage" :total-size="totalSize"
        @changePageSize="changePageSize" @changeCurrentPage="changeCurrentPage" />
      <AddEditDialog ref="addEditDialog" :now-chance-stau="nowChanceStau" :title-text="titleText"
        :edit-object="editObject" :show.sync="showAddEditDialog" @closeDialog="closeDialog" @cancelDialog="cancel" />
    </template>
  </BaseMainSlot>
</template>

<script>
import ActionBar from "@/components/ActionBar";
import Pagination from "@/components/Pagination";
import CategoryBar from "@/components/CategoryBar";
import BaseMainSlot from "@/components/BaseMainSlot/kong-new.vue";
import AddEditDialog from "./components/add-edit-dialog.vue";
import ExportBtn from "@/components/ExportBtn";

import { mymixin } from "@/utils/mixin";
import { mapGetters } from "vuex";

import HealthTaskHandlingApi from "@/api/health-management/health-task-handling";
import HealthManagementApi from "@/api/health-management/health-task-management";
import BatchApi from "@/api/batch-mange/index";
import StaffApi from "@/api/basic-info-manage/staff";
import FishPondApi from "@/api/basic-info-manage/fishPond"; // 鱼塘信息
export default {
  name: "StaffManage",
  components: {
    ExportBtn,
    ActionBar,
    Pagination,
    BaseMainSlot,
    AddEditDialog,
    CategoryBar,
  },
  mixins: [mymixin],
  data() {
    return {
      searchObj: {},
      // 查询条件：
      productionBatchId: undefined,
      discoverStaffId: undefined,
      happenTime: undefined,  // 发现时间
      dealTime: undefined,    // 处理时间
      dealFlag: undefined,
      completeFlag: undefined,
      batchList: [],          // 查询-批次
      pondList: [],            // 查询-鱼塘
      fishPondId: undefined,   // 查询-鱼塘id
      staffList: [],
      checkedIdList: [],
      routerPath: '',  // 当前路由
      mark: "",
      categoryList: [
        { id: 0, mark: "dealFlagNone", name: "未处理", value: false },
        { id: 1, mark: "dealFlag", name: "已处理", value: true },
        { id: 4, mark: "completeFlag", name: "已完成", value: true },
      ],
    };
  },
  computed: {
    ...mapGetters({
      judgePermission: "permission/judgePermission",
    }),
  },
  watch: {},
  created() {
    this.routerPath = this.$route.path
    this.queryBatch();
    this.queryStaff();
    this.queryPond()
    if (this.routerPath == '/healthTaskManagement-sr') {
      this.categoryList.splice(0, 2)
    }
  },
  mounted() { },
  methods: {
    searchPage() {
      this.currentPage = 1
      this.queryPageList();
      setTimeout(() => {
        this.queryPageList();
      }, 200);
    },
    // 查询-获取鱼塘
    queryPond() {
      FishPondApi.queryByCondition().then(res => {
        this.pondList = res.data
        // console.log('鱼塘***this.pondList',this.pondList);
      })
    },
    categoryBar(item) {
      this.currentPage = 1;
      this.dealFlag = undefined;
      this.completeFlag = undefined;

      console.log(item.mark)
      if (item.mark === "dealFlagNone") { this.dealFlag = false; this.completeFlag = false; }
      if (item.mark === "dealFlag") { this.dealFlag = true; this.completeFlag = false; }
      if (item.mark === "completeFlag") { this.dealFlag = true; this.completeFlag = true; }
      this.mark = item.mark
      this.queryPageList();
      console.log(this.dealFlag, this.completeFlag, this.mark)
    },
    expandChange(row, e) {
      this.queryInputPondDetail(row);
    },
    queryBatch() {
      BatchApi.queryByCondition({}).then((res) => {
        this.batchList = res.data;
      });
    },
    queryStaff() {
      StaffApi.queryByCondition().then(res => {
        this.staffList = res.data;
      })
    },
    queryInputPondDetail(v) {
      let params = {
        diseaseRecordId: v.diseaseRecordId,
      };
      HealthTaskHandlingApi.queryByDiseaseRecordId(params).then((res) => {
        if (res.success) {
          this.tableData[v.expandIndex]["diseaseDealList"] = res.data;
        }
      });
    },
    queryPageList() {
      let params = {
        page: this.currentPage,
        size: this.pageSize,
        entity: {},
      };
      if (this.dealFlag !== undefined) params.entity.dealFlag = this.dealFlag;
      if (this.completeFlag !== undefined) params.entity.completeFlag = this.completeFlag;

      if (this.productionBatchId) params.entity.productionBatchId = this.productionBatchId;
      if (this.discoverStaffId) params.entity.discoverStaffId = this.discoverStaffId;
      if (this.fishPondId) params.entity.fishPondId = this.fishPondId; // 查询-鱼塘
      if (this.dealTime) {
        params.entity.dealStartTime = this.dealTime[0];
        params.entity.dealEndTime = this.dealTime[1].replace(
          "00:00:00",
          "24:00:00"
        );
      }
      if (this.happenTime) {
        params.entity.happenStartTime = this.happenTime[0];
        params.entity.happenEndTime = this.happenTime[1].replace(
          "00:00:00",
          "24:00:00"
        );
      }
      this.searchObj = JSON.parse(JSON.stringify(params.entity))
      HealthManagementApi.queryPageByCondition(params).then((res) => {
        if (res.success === true) {
          let data = res.data || {};
          this.totalSize = data.totalElements;
          // 赋值数组
          this.tableData = data.content;
          this.tableData.forEach((item, index) => {
            item["expandIndex"] = index;
          });
          this.addblankmet();
          this.resetActionBar();
        }
      });
    },
    // 单个删除
    delOne(data) {
      console.log(data)
      this.checkedIdList = [data.diseaseRecordId]
      this.$confirm("此操作将永久删除该项, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.delmessage()
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 表格删除
    delmessage() {
      HealthManagementApi.delListById({ idList: this.checkedIdList }).then(
        (res) => {
          if (res.success) {
            this.$message.success("删除成功");
            this.queryPageList();
            this.resetActionBar();
          } else {
            this.$message.error(res.message);
          }
        }
      );
    },
    changePageSize(pageSize) {
      this.pageSize = pageSize;
      this.queryPageList();
    },
    changeCurrentPage(currentPage) {
      this.currentPage = currentPage;
      this.queryPageList();
    },
    selectAll(list) {
      let notvalue = true;
      list.forEach((item) => {
        if (!item.diseaseRecordId) {
          notvalue = false;
        }
      });
      if (notvalue === false) {
        this.$message.warning("不可选择空数据！");
      }
    },
    select(list) {
      let notvalue = true;
      list.forEach((item) => {
        if (!item.diseaseRecordId) {
          notvalue = false;
        }
      });
      if (notvalue === false) {
        this.$message.warning("不可选择空数据！");
      }
    },
    handleSelectionChange(list) {
      this.checkedIdList = [];
      let notvalue = true;
      let emptyList = [];
      this.checkedIdList = list.map((item) => {
        if (item.diseaseRecordId) {
          return item.diseaseRecordId;
        } else {
          notvalue = false;
          emptyList.push(item);
          return "";
        }
      });
      if (notvalue === false) {
        // this.$message.warning("不可选择空数据！");
        this.toggleNoSelection(emptyList);
        return;
      }
      if (this.checkedIdList.length >= 1) this.delActive = true;
      else this.delActive = false;
    },
    // 添加
    add() {
      this.nowChanceStau = "add";
      this.titleText = "添加";
      this.addActive = false;
      this.delActive = false;
      this.showAddEditDialog = true;
    },
    // 修改
    edit(row) {
      if (row.diseaseRecordId) {
        this.editObject = { ...row };
        this.nowChanceStau = "edit";
        this.titleText = "修改";
        this.addActive = false;
        this.delActive = false;
        this.showAddEditDialog = true;
      } else {
        this.editObject = {};
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.table-expand-box {
  width: 100%;
  color: #333333;
  text-align: left;
  cursor: pointer;

  .drugInfo {
    width: 100%;
    display: flex;
    justify-content: space-between;
    align-items: center;
    background: #9bb8d5;
    color: #ffffff;

    .serialNum {
      width: 160px;
      text-align: center;
    }

    .table-expand {
      width: calc(100% - 160px);
      display: flex;
      justify-content: flex-start;
      padding-left: 20px;
      box-sizing: border-box;

      .table-expand-item {
        width: 25%;
        display: flex;
        justify-content: flex-start;
        flex-wrap: wrap;
        padding: 10px 5px;
        font-size: 14px;

        .titelStyle {
          width: 100px;
          color: #999999;
          padding-right: 10px;
          box-sizing: border-box;
          text-align: right;
        }

        .textStyle {
          width: calc(100% - 100px);
          color: #333333;
        }
      }
    }
  }

  .table-expand-drug {
    background: #ffffff;
    border-bottom: 1px solid #cecece;

    .table-expand-drugInfo {
      width: calc(100% - 40px);
      display: flex;
      justify-content: flex-start;
      align-items: center;

      .table-expand-item {
        width: 25%;
        display: flex;
        justify-content: flex-start;
        flex-wrap: wrap;
        padding: 10px 5px;
        font-size: 14px;

        .titelStyle {
          width: 100px;
          color: #999999;
          padding-right: 10px;
          box-sizing: border-box;
          text-align: right;
        }

        .textStyle {
          width: calc(100% - 100px);
          color: #333333;
        }
      }
    }
  }

  .drugInfo:hover {
    background: #82a5c8;
  }

  .table-expand-drug:hover {
    background: #f6f6f6;
  }
}

::v-deep .el-table tr:hover {
  background: aliceblue !important;
}

::v-deep .el-table__expanded-cell:hover {
  background: aliceblue !important;
}
</style>
